package com.study.spmongodb.wwj.juc.utils.complete;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/16 21:37
 */
public class CompletableFutureExample2 {

    public static void main(String[] args) throws InterruptedException {
        // supplyAsync();
        // runAsync();
        completed("hello scalal");

        Thread.currentThread().join();
    }

    private static void anyOf() {
        CompletableFuture.anyOf(CompletableFuture.runAsync(() -> {
            System.out.println("obj====start");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("obj=====end");
        }).whenComplete((v, t) -> {
            System.out.println("task over");
        }));
    }

    private static CompletableFuture<Void> completed(String data) {
        return CompletableFuture.completedFuture(data).thenAccept(System.out::println);
    }

    private static void runAsync() {
        CompletableFuture.runAsync(() -> {
            System.out.println("obj====start");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("obj=====end");
        }).whenComplete((v, t) -> {
            System.out.println("task over");
        });
    }


    private static void supplyAsync() {
        CompletableFuture.supplyAsync(Object::new)
                .thenAccept(obj -> {
                    try {
                        System.out.println("-----obj ---start");
                        TimeUnit.SECONDS.sleep(5);
                        System.out.println("-----obj ---end---");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).runAfterBoth(CompletableFuture.supplyAsync(() -> "Hello")
                        .thenAccept(str -> {
                            System.out.println(str);
                        }),
                () -> System.out.println("=====finished==both"));
    }
}
